/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.yuhanginfo.modules.sys.web;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.google.common.collect.Lists;
import com.yuhanginfo.common.config.Global;
import com.yuhanginfo.common.persistence.Page;
import com.yuhanginfo.common.web.BaseController;
import com.yuhanginfo.common.utils.DateUtils;
import com.yuhanginfo.common.utils.StringUtils;
import com.yuhanginfo.common.utils.excel.ExportExcel;
import com.yuhanginfo.common.utils.excel.ImportExcel;
import com.yuhanginfo.modules.sys.entity.Area;
import com.yuhanginfo.modules.sys.entity.FreeWaybill;
import com.yuhanginfo.modules.sys.entity.SysAddress;
import com.yuhanginfo.modules.sys.entity.Credit;
import com.yuhanginfo.modules.sys.entity.Goods;
import com.yuhanginfo.modules.sys.entity.InvoiceInfo;
import com.yuhanginfo.modules.sys.entity.Orders;
import com.yuhanginfo.modules.sys.entity.OrdersDetail;
import com.yuhanginfo.modules.sys.entity.Store;
import com.yuhanginfo.modules.sys.entity.StoreWarehouse;
import com.yuhanginfo.modules.sys.entity.TransactionHistory;
import com.yuhanginfo.modules.sys.entity.User;
import com.yuhanginfo.modules.sys.entity.UserStore;
import com.yuhanginfo.modules.sys.entity.Waybill;
import com.yuhanginfo.modules.sys.entity.YongUser;
import com.yuhanginfo.modules.sys.entity.exportGoods;
import com.yuhanginfo.modules.sys.service.AreaService;
import com.yuhanginfo.modules.sys.service.FreeWaybillService;
import com.yuhanginfo.modules.sys.service.SysAddressService;
import com.yuhanginfo.modules.sys.service.CreditService;
import com.yuhanginfo.modules.sys.service.GoodsService;
import com.yuhanginfo.modules.sys.service.InvoiceInfoService;
import com.yuhanginfo.modules.sys.service.OrdersDetailService;
import com.yuhanginfo.modules.sys.service.OrdersService;
import com.yuhanginfo.modules.sys.service.StoreService;
import com.yuhanginfo.modules.sys.service.StoreWarehouseService;
import com.yuhanginfo.modules.sys.service.SystemService;
import com.yuhanginfo.modules.sys.service.TransactionHistoryService;
import com.yuhanginfo.modules.sys.service.WaybillService;
import com.yuhanginfo.modules.sys.service.YongUserService;
import com.yuhanginfo.modules.sys.utils.UserUtils;

/**
 * 订单管理Controller
 * @author yangs
 * @version 2017-09-18
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/orders")
public class OrdersController extends BaseController {
	
	private static final Logger logger = LoggerFactory.getLogger(OrdersController.class);
	
	@Autowired
	private OrdersService ordersService;
	@Autowired
	private StoreService storeService;
	
	@Autowired
	private OrdersDetailService ordersDetailService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private StoreWarehouseService storeWarehouseService;
	@Autowired
	private WaybillService waybillService;
	@Autowired
	private CreditService creditService;
	@Autowired
	private TransactionHistoryService transactionHistoryService;
	@Autowired
	private InvoiceInfoService invoiceInfoService;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private YongUserService yongUserService;
	@Autowired
	private SysAddressService addressService;
	@Autowired
	private AreaService areaService;
	@Autowired
	private FreeWaybillService freeWaybillService;
	
	private static final String STORE = "store";
	private static final String ORDERS = "orders";
	private static final String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
	private static final String REDIRECT = "redirect:";
	private static final String STORECODE = "storeCode";
	private static final String REPLACEORDER = "modules/sys/order/replaceOrder";
	private static final String EXPORTORDERLIST = "exportOrderList";
	private static final String USERID = "userId";
	
	@ModelAttribute
	public Orders get(@RequestParam(required=false) String id) {
		Orders entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = ordersService.get(id);
		}
		if (entity == null){
			entity = new Orders();
		}
		return entity;
	}
	
	@RequiresPermissions("sys:orders:view")
	@RequestMapping(value = {"list", ""})
	public String list(Orders orders, HttpServletRequest request, HttpServletResponse response, Model model) {
		User us = UserUtils.getUser();
		orders.setSysUserName(us.getId());
		Page<Orders> page = ordersService.findPage(new Page<Orders>(request, response), orders); 
		List<Orders> list=page.getList();
		for (Orders orders2 : list) {
			long st=new Date().getTime();
			if(orders2.getSendFinishTime()!=null){
			long st2=orders2.getSendFinishTime().getTime();
			long st3=st-st2-1000*60*60*24*7;
			if("4".equals(orders2.getState())&&st3>0){
				orders2.setState("5");
			}
			}
		}
		page.setList(list);
		List<Store> store=storeService.storeUserList(us.getId());
		model.addAttribute(STORE, store);
		model.addAttribute(ORDERS, orders);
		model.addAttribute("page", page);
		return "modules/sys/order/ordersList";
	}

	/**
	 * 导出订单数据
	 * @param user
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("sys:orders:view")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(Orders orders, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "订单数据"+DateUtils.getDate(YYYYMMDDHHMMSS)+".xlsx";
        	User us = UserUtils.getUser();
    		orders.setSysUserName(us.getId());
            Page<Orders> page = ordersService.selectImportOrder(new Page<Orders>(request, response, -1), orders);
    		new ExportExcel("订单数据", Orders.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			logger.info("exportFile", e);
		}
		return REDIRECT + adminPath + "/sys/orders/list?repage";
    }
	
	
	@RequiresPermissions("sys:orders:view")
	@RequestMapping(value = "form")
	public String form( Model model,String id,String tagUrl,String tagName) {
		/*0: 全部订单详情
		 *1 : 待分配订单详情
		 * 2 : 待处理订单详情
		 * 3: 异常订单详情
		 */
		Orders orders= ordersService.get(id);
		InvoiceInfo invoiceIn = invoiceInfoService.selectByOrdersCode(orders.getCode());
		List<OrdersDetail> orderDetail=ordersDetailService.selectByOrderCode(orders.getCode());
		Double goodsMoney=0.00;
		for (OrdersDetail ordersDetail : orderDetail) {
			if(null == ordersDetail.getFhNum()||"".equals(ordersDetail.getFhNum())){
				ordersDetail.setFhNum("0");
			}
			Double num=Double.valueOf(ordersDetail.getNum());
			Double price=Double.valueOf(ordersDetail.getPrice());
			ordersDetail.setTotalMoney(String.valueOf(num*price));
			goodsMoney=goodsMoney+(num*price);
		}
		orders.setGoodsTotalMoney(goodsMoney.toString());
		model.addAttribute("orderDetail", orderDetail);
		model.addAttribute(ORDERS, orders);
		model.addAttribute("invoiceIn", invoiceIn);
		model.addAttribute("tagUrl", tagUrl);
		model.addAttribute("tagName", tagName);
		return "modules/sys/order/ordersForm";
	}

	
	@RequiresPermissions("sys:orders:edit")
	@RequestMapping(value = "delete")
	public String delete(Orders orders, RedirectAttributes redirectAttributes) {
		ordersService.delete(orders);
		addMessage(redirectAttributes, "删除订单管理成功");
		return REDIRECT+Global.getAdminPath()+"/sys/orders/?repage";
	}

	@RequiresPermissions("sys:orders:view")
	@RequestMapping(value = "assignSaleMan")
	public String assignSaleMan(Orders orders, HttpServletRequest request, HttpServletResponse response, Model model) {
		User us = UserUtils.getUser();
		orders.setSysUserName(us.getId());
		Page<Orders> page = ordersService.assignSaleMan(new Page<Orders>(request, response), orders); 
	   for(int i=page.getList().size()-1;i>=0;i--){
		      if(null != page.getList().get(i).getBuyStoreName() && !"".equals(page.getList().get(i).getBuyStoreName())
		    		  && null != page.getList().get(i).getSuoStore() && !"".equals(page.getList().get(i).getSuoStore())
		    		  && page.getList().get(i).getBuyStoreName().trim().equals(page.getList().get(i).getSuoStore().trim())){
		    			   page.getList().remove(i);
		      }
	   }
		List<Store> store=storeService.storeUserList(us.getId());
		List<User> user=systemService.saleManList(us.getId());
		model.addAttribute("user", user);
		model.addAttribute(STORE, store);
		model.addAttribute("page", page);
		return "modules/sys/order/assignSaleManList";
	}
	
	@RequiresPermissions("sys:orders:edit")
	@RequestMapping(value = "upSaleMan")
	public String upSaleMan(String id,String name) {
		Orders ord=new Orders();
		ord.setId(id);
		ord.setSysUserId(name);
		ordersService.upSaleMan(ord);
		return REDIRECT+Global.getAdminPath()+"/sys/orders/assignSaleMan?repage";
	}
	
	//待处理订单
	@RequiresPermissions("sys:orders:view")
	@RequestMapping(value = "handleOrderList")
	public String handleOrderList(Orders orders, HttpServletRequest request, HttpServletResponse response, Model model) {
		User us = UserUtils.getUser();
		orders.setSysUserName(us.getId());
		Page<Orders> page = ordersService.handleOrderList(new Page<Orders>(request, response), orders); 
		List<Store> store=storeService.storeUserList(us.getId());
		List<User> user=systemService.saleManList(us.getId());
		model.addAttribute("user", user);
		model.addAttribute(STORE, store);
		model.addAttribute("page", page);
		return "modules/sys/order/handleOrderList";
	}
	
	//发货详情
	@RequiresPermissions("sys:orders:view")
	@RequestMapping(value = "deliverGoods")
	public String deliverGoods( Model model,String code,String storeCode) {
		Orders orders= ordersService.selectByCode(code);
		List<OrdersDetail> orderDetail=ordersDetailService.selectByOrderCode(code);
		for (OrdersDetail ordersDetail : orderDetail) {
			if(ordersDetail.getFhNum()==null||ordersDetail.getFhNum()==""){
				ordersDetail.setFhNum("0");
			}
			Integer num=Integer.parseInt(ordersDetail.getNum());
			Integer fh=0;
			if(ordersDetail.getFhNum()!=null&&ordersDetail.getFhNum()!=""){
				fh=Integer.parseInt(ordersDetail.getFhNum());
			}
			ordersDetail.setYuNum(String.valueOf(num-fh));
		}
		model.addAttribute("code", code);
		model.addAttribute(STORECODE, storeCode);
		model.addAttribute("orderDetail", orderDetail);
		model.addAttribute(ORDERS, orders);
		return "modules/sys/order/deliverGoods";
	}
	
	   //确认发货数量
		@RequiresPermissions("sys:orders:view")
		@RequestMapping(value = "confirmGoodsNum")
		public String confirmGoodsNum( Model model,String code,OrdersDetail ordersDetail,String storeCode) {
			List<OrdersDetail> orderDetail1=new ArrayList<>();
			List<OrdersDetail> orderDetails=ordersDetailService.selectByOrderCode(code);
			for (OrdersDetail ordersDetails : orderDetails) {
				Integer num=Integer.parseInt(ordersDetails.getNum());
				Integer fh=0;
				if(ordersDetails.getFhNum()!=null&&ordersDetails.getFhNum()!=""){
					fh=Integer.parseInt(ordersDetails.getFhNum());
				}
				if((num-fh)!=0){
					ordersDetails.setYuNum(String.valueOf(num-fh));
					orderDetail1.add(ordersDetails);
				}
			}
			User us = UserUtils.getUser();
			StoreWarehouse storeWarehouse=new StoreWarehouse();
			storeWarehouse.setSysUserId(us.getId());
			storeWarehouse.setOrdersCode(code);
			storeWarehouse.setStoreCode(storeCode);
			Orders orders= ordersService.selectByCode(code);
			
			List<StoreWarehouse> storeWarehouseList=storeWarehouseService.selectUseStoreWarehouse(orders.getBuyStoreCode());
			model.addAttribute("storeWarehouseList", storeWarehouseList);
			model.addAttribute("orderDetail1", orderDetail1);
			model.addAttribute("ordersDetail", ordersDetail);
			model.addAttribute("code", code);
			return "modules/sys/order/deliverGoodsSave";
		}
		//根据所选择的仓库显示其商品
		@ResponseBody
		@RequiresPermissions("sys:orders:view")
		@RequestMapping(value = "showGoods")
		public List<String> showGoods( Model model,String id,String[] goodsCode) {
			List<StoreWarehouse> list=storeWarehouseService.selectById(id);
			List<String> list0=new ArrayList<>();
			for (StoreWarehouse storeWarehouse : list) {
				list0.add(storeWarehouse.getGoodsCode());
			}
			List<String> list1=new ArrayList<>();
			for (int i = 0; i < goodsCode.length; i++) {
				boolean b=list0.contains(goodsCode[i]);
				if(!b){
					list1.add(goodsCode[i]);
				}
			}
			
			return list1;
		}
		
		
		//发货保存
		@RequiresPermissions("sys:orders:edit")
		@RequestMapping(value = "saveGoodsNum")
		public String saveGoodsNum(HttpServletRequest request) {
			String code = request.getParameter("code");
			String[] goodsCnName = request.getParameterValues("goodsCnName");
			String[] fhNum = request.getParameterValues("fhNum");
			String cnName = request.getParameter("cnName");
			String[] goodsCode = request.getParameterValues("goodsCode");
			String logistics = request.getParameter("logistics");
			String logisticsCode = request.getParameter("logisticsCode");
			Integer tnum=0;
			List<OrdersDetail> orderDetails=ordersDetailService.selectByOrderCode(code);
			List<Waybill> waybill=waybillService.selectByOrderCode(code);
			Integer st=0;
			for (Waybill waybill2 : waybill) {
				st=st+Integer.parseInt(waybill2.getNum());
			}
			for (OrdersDetail ordersDetail : orderDetails) {
				tnum=tnum+Integer.parseInt(ordersDetail.getNum());
			}
			Integer fnum=0;
			 for (int i = 0; i < goodsCnName.length; i++) {
				 fnum=fnum+Integer.parseInt(fhNum[i]);
				 Waybill way=new Waybill();
				 way.setGoodsCnName(goodsCnName[i]);
				 way.setGoodsCode(goodsCode[i]);
				 way.setNum(fhNum[i]);
				 way.setOrdersCode(code);
				 way.setWaybillCode("WL"+new Date().getTime());
				 way.setLogistics(logistics);
				 way.setLogisticsCode(logisticsCode);
				 way.setCreateDate(new Date());
				 way.setStatus("0");
				 User us = UserUtils.getUser();
				 way.setCreateBy(us);
				 way.setWarehouseId(cnName);
				 waybillService.save(way);
			}
			 Orders orders=new Orders();
			 orders.setCode(code);
			if((tnum-st)>fnum){
				orders.setState("3");
				orders.setUpdateDate(new Date());
				ordersService.upStatus(orders);
			}else{
				orders.setSendFinishTime(new Date());
				orders.setState("4");
				orders.setUpdateDate(new Date());
				ordersService.upStatus(orders);
			}
			
			return REDIRECT+Global.getAdminPath()+"/sys/orders/handleOrderList?repage";
		}
	
		//个人可用信用额度
		@ResponseBody
		@RequiresPermissions("sys:orders:edit")
		@RequestMapping(value = "kYong")
		public Map<String,Object> kYong(String id) {
	        Map<String,Object> map=new HashMap<>();
	        Credit credit=creditService.selectByUserId(id);
	        if(credit!=null){
	        map.put("kyong", (credit.getMoney().add(credit.getRechargeMoney())).subtract(credit.getUseMoney()));
	        }else{
	        	map.put("kyong", 0);
	        }
			return map;
		}
		
		//发货保存
		@RequiresPermissions("sys:orders:edit")
		@RequestMapping(value = "addFreight")
		public String addFreight(String freight,String userId ,String orderCode,String orderId,String chaMoney) {
			User us = UserUtils.getUser();
			Orders or=ordersService.get(orderId);
			Orders orders= new Orders();
			Double mo=Double.valueOf(or.getPayMoney());
			orders.setFreight(freight);
			orders.setCode(orderCode);
			orders.setId(orderId);
			orders.setPayMoney(String.valueOf(mo-Double.valueOf(chaMoney)));
			orders.setUpdateDate(new Date());
			orders.setUpdateBy(us);
			orders.setState("8");
			ordersService.updateMoney(orders);
			TransactionHistory transactionHistory=new TransactionHistory();
			transactionHistory.setCode("XY"+new Date().getTime());
			transactionHistory.setUserId(userId);
			transactionHistory.setCreateDate(new Date());
			transactionHistory.setCreateBy(us);
			if(Double.valueOf(chaMoney)>=0){
				transactionHistory.setType("5");
			}else{
				transactionHistory.setType("6");
			}
			transactionHistory.setMoney(new BigDecimal(chaMoney));
			transactionHistory.setPayType(0);
			transactionHistoryService.save(transactionHistory);
			Credit credit=new Credit();
			Credit cr=creditService.selectByUserId(userId);
     
			credit.setUseMoney(cr.getUseMoney().subtract(new BigDecimal(chaMoney)));
			credit.setUserId(userId);
			credit.setUpdateDate(new Date());
			credit.setUpdateBy(us);
			creditService.updateUseMoney(credit);
			
		return REDIRECT+Global.getAdminPath()+"/sys/orders/handleOrderList?repage";
		}
			
		//异常订单处理
		@RequiresPermissions("sys:orders:view")
		@RequestMapping(value = "abnormalOrderList")
		public String abnormalOrderList(Orders orders, HttpServletRequest request, HttpServletResponse response, Model model) {
			User us = UserUtils.getUser();
			orders.setSysUserName(us.getId());
			Page<Orders> page = ordersService.abnormalOrderList(new Page<Orders>(request, response), orders); 
			List<Store> store=storeService.storeUserList(us.getId());
			List<User> user=systemService.saleManList(us.getId());
			model.addAttribute("user", user);
			model.addAttribute(STORE, store);
			model.addAttribute("page", page);
			return "modules/sys/order/abnormalOrderList";
		}
		
		//异常订单处理
		@RequiresPermissions("sys:orders:view")
		@RequestMapping(value = "abnormalHandle")
		public String abnormalHandle(Orders orders,String remarks,String id,String historyState) {
			User us = UserUtils.getUser();
			orders.setRemarks(remarks);
			orders.setState("7");
			orders.setHistoryState(historyState);
			orders.setUpdateBy(us);
			orders.setUpdateDate(new Date());
			if("4".equals(historyState)||"5".equals(historyState)){
				orders.setSendFinishTime(new Date());
			}
			orders.setId(id);
			ordersService.updateHistoryState(orders);
			return REDIRECT+Global.getAdminPath()+"/sys/orders/abnormalOrderList?repage";
		}
		
		//异常订单处理
		@RequiresPermissions("sys:orders:view")
		@RequestMapping(value = "removeHandle")
		public String removeHandle(Orders orders,String id,String historyState) {
			User us = UserUtils.getUser();
			if("4".equals(historyState)||"5".equals(historyState)){
				orders.setState("4");
				orders.setSendFinishTime(new Date());
			}else{
				orders.setState(historyState);
			}
			orders.setRemarks(null);
			orders.setHistoryState(null);
			orders.setUpdateBy(us);
			orders.setId(id);
			orders.setUpdateDate(new Date());
			ordersService.removeHistoryState(orders);
			return REDIRECT+Global.getAdminPath()+"/sys/orders/abnormalOrderList?repage";
		}
		
	 /*
	  * 代下单管理
	  */
	 //模板下载
		@RequiresPermissions("sys:orders:view")
		@RequestMapping(value = "/exportReplaceOrder")
	    public void exportReplaceOrder(HttpServletResponse response, RedirectAttributes redirectAttributes) {
			try {
	            String fileName = "代替下单导入模板.xlsx";
	    		List<Goods> list = Lists.newArrayList(); 
	    		new ExportExcel("", Goods.class, 2).setDataList(list).write(response, fileName).dispose();
			} catch (Exception e) {
				logger.info("exportReplaceOrder",e);
				addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
			}
			
	    }	
		
	//代下单页面显示	
	@RequiresPermissions("sys:orders:view")
	@RequestMapping(value = "/showReplaceOrder")
	public String showReplaceOrder(Model model,Orders orders,String ps) {
		User us = UserUtils.getUser();
		List<Store> store=storeService.storeSaleList(us.getId());
		model.addAttribute(STORE, store);
		model.addAttribute("ps", ps);
		model.addAttribute(ORDERS, orders);
		return REPLACEORDER;
	}	
	
	//导入数据
	@RequiresPermissions("sys:orders:view")
	@RequestMapping(value = "/importOrders")
	public String importOrders(Model model,MultipartFile file,String storeCode,String useName,String ppType,HttpSession session,Orders orders){
		try{
			User us = UserUtils.getUser();
			List<Store> store=storeService.storeSaleList(us.getId());
			String fileName=file.getOriginalFilename();
			if(fileName.indexOf("代替下单")!=-1){
			List<Goods> list0=new ArrayList<>();
			Integer stg=0;
			if(storeCode!=null && storeCode!="" ){
				ImportExcel ei = new ImportExcel(file, 1, 0);
				Integer successGoods=0;
				List<Goods> list = ei.getDataList(Goods.class);
				for (Goods goods : list) {
					Goods goods1=new Goods();
					Goods goods2=new Goods();
					Goods goods3=new Goods();
					Pattern p = Pattern.compile("\\s*|\t|\r|\n");
					Matcher finalGoodsName = p.matcher(goods.getCnName());
					Matcher finalPartsCode = p.matcher(goods.getPartsCode());
					String parts=finalPartsCode.replaceAll("");
					String useParts = "";
					if(parts.indexOf('E')!=-1){
						String st=parts.substring(0,parts.indexOf('E'));
						useParts=st.replace(".", "");
					}else{
						useParts=parts;
					}
					goods.setPartsCode(useParts);
					goods1.setCnName(finalGoodsName.replaceAll(""));
					goods1.setStoreCode(storeCode);
					//配件
					if("0".equals(ppType)){
						goods2.setPartsCode(useParts);
					}
					//厂家编号
					if("1".equals(ppType)){
						goods2.setVenderCode(useParts);
					}
					//物料编号
					if("2".equals(ppType)){
						goods2.setCode(useParts);
					}
					goods2.setStoreCode(storeCode);
					goods3.setStoreCode(storeCode);
					goods3.setCnName(finalGoodsName.replaceAll(""));
					goods3.setPartsCode(useParts);
					List<Goods> partsCode=goodsService.replaceOrder(goods2);
					if(!partsCode.isEmpty()){
					    for (Goods goods4 : partsCode) {
							Goods good=new Goods();
							String img=goods4.getImage();
		                    if(img!=null && img!=""){
		                    	String[] images=img.split(";");
		                    	good.setImage(images[0]);
		                    }
							good.setPrice(goods4.getVipPrice().doubleValue());
							good.setCnName(goods4.getCnName());
							good.setPartsCode(goods4.getPartsCode());
							good.setGoodsNum(goods.getGoodsNum());
							good.setId(goods4.getId());
							good.setFailReason("0");
							BigDecimal st=new BigDecimal(goods.getGoodsNum()).multiply(goods4.getVipPrice());
							good.setTotalMoney(st);
							list0.add(good);
							stg=stg+1;
						}
						successGoods++;
					}else{
						goods.setFailReason("1");
						list0.add(goods);
					}
				}
			   model.addAttribute("list", list0);
			   model.addAttribute("successGoods", successGoods);
			   session.setAttribute(EXPORTORDERLIST, list0);
			}
			model.addAttribute("usesssLength", stg);
			model.addAttribute(USERID, useName);
			session.setAttribute(USERID, useName);
			model.addAttribute("saleMan", us.getId());
		    orders.setBuyStoreCode(storeCode);
			model.addAttribute(STORECODE, storeCode);
			}else{
				model.addAttribute("mess", 1);
				
			}
			model.addAttribute(STORE, store);
			model.addAttribute("ppType",ppType);
			model.addAttribute("userType",us.getUserType());
			orders.setBuyStoreCode(storeCode);
			return REPLACEORDER;
		}catch(Exception e){
			logger.info("importOrders",e);
		}
		return "";
	}	
	//加载会员
	@ResponseBody
	@RequiresPermissions("sys:orders:view")
	@RequestMapping(value = "/userList")
	public List<YongUser> userList(String storeCode){
		User us = UserUtils.getUser();
		YongUser user=new YongUser();
		user.setBeSysUserId(us.getId());
		return yongUserService.selectVipByStoreCode(user);
	}
	
    //删除
	@SuppressWarnings("unchecked")
	@RequiresPermissions("sys:orders:edit")
	@RequestMapping(value = "/delectOrder")
	public String delectOrder(String goodsName,Model model,HttpSession session,String storeCode,String userId, String successGoods){
		List<Goods> list=(List<Goods>) session.getAttribute(EXPORTORDERLIST);
		List<Goods> useList=new ArrayList<>();
		List<Goods> useLi=new ArrayList<>();
		for (Goods goods : list) {
			if(!goods.getCnName().equals(goodsName)){
				useList.add(goods);
			}
		}
		for (Goods goods : useList) {
			if("0".equals(goods.getFailReason())){
				useLi.add(goods);
			}
		}
		User us = UserUtils.getUser();
		List<Store> store=storeService.storeSaleList(us.getId());
		model.addAttribute("list", useList);
		model.addAttribute("usesssLength", useLi.size());
		model.addAttribute(STORE, store);
		model.addAttribute(USERID, userId);
		model.addAttribute("successGoods", successGoods);
		model.addAttribute(STORECODE, storeCode);
		session.setAttribute(EXPORTORDERLIST, useList);
		model.addAttribute("saleMan", us.getId());
		return REPLACEORDER;
	}
	
	////快速下单导出
    @SuppressWarnings("unchecked")
    @RequiresPermissions("sys:orders:view")
    @RequestMapping(value = "/exportOrders")
    public void exportOrders(HttpSession session,HttpServletRequest request, HttpServletResponse response) throws IOException{
    	List<Goods> list0=(List<Goods>) session.getAttribute(EXPORTORDERLIST);
		List<exportGoods> list=new ArrayList<>();
		for (int i = 0; i < list0.size(); i++) {
			exportGoods exports =new exportGoods();
			if("0".equals(list0.get(i).getFailReason())){
				exports.setFailReason("成功");
			}else if("1".equals(list0.get(i).getFailReason())){
				exports.setFailReason("配件编号匹配失败");
			}else if("2".equals(list0.get(i).getFailReason())){
				exports.setFailReason("商品名称匹配失败");
			}else{
				exports.setFailReason("商品配件与编号不一致");
			}
			exports.setGoodsName(list0.get(i).getCnName());
			exports.setPartsCode(list0.get(i).getPartsCode());
			exports.setGoodsNum(list0.get(i).getGoodsNum());
			list.add(exports);
		}
		String fileName = "代下单匹配"+DateUtils.getDate(YYYYMMDDHHMMSS)+".xlsx";
		new ExportExcel("代下单匹配结果", exportGoods.class).setDataList(list).write(response, fileName).dispose();
		
    }
    
    
    //后台下单页面
    @SuppressWarnings("unchecked")
    @RequiresPermissions("sys:orders:view")
	@RequestMapping(value = "replaceShow")
	public String replaceSaveOrder(HttpSession session,String userId,String storeCode,Model model) {
    	User user=ordersDetailService.Item(userId);
    	Store store=storeService.sArea(storeCode);
    	Store storeInfo=storeService.storeInfo(storeCode);
    	String storeId=store.getClassify();
    	List<FreeWaybill> freeWay=freeWaybillService.selectAll();
    
    	String userIds=(String) session.getAttribute(USERID);
    	List<Goods> list=(List<Goods>) session.getAttribute(EXPORTORDERLIST);
    	List<Goods> list0=new ArrayList<>();
    	for (Goods goods : list) {
    		if("0".equals(goods.getFailReason())){
    			list0.add(goods);
    		}	
		}
    	List<SysAddress> address=addressService.selectByUseId(userIds);
    	SysAddress addr=null;
    	if(!address.isEmpty()){
    	for (SysAddress address2 : address) {
			if("1".equals(address2.getIsDef())){
				addr=address2;
			}
		}
    	if(addr==null){
    		addr=address.get(0);
    	}else{
    		String money="";
    		SysAddress addresss=addressService.get(addr.getId());
    		
    		String province=addresss.getProvince();
    		for (FreeWaybill freeWaybill : freeWay) {
    			 if((freeWaybill.getSendAreaId().equals(storeId))&&freeWaybill.getReceiveAreaId().equals(province)){
    				 money=freeWaybill.getMoney();
    			 }
    			
    		}
    		model.addAttribute("money",money);
    	}
    	}
    	model.addAttribute("addr", addr);
    	model.addAttribute("address",address );
    	model.addAttribute("list0", list0);
    	model.addAttribute(USERID, userId);
    	model.addAttribute(STORECODE, storeCode);
    	model.addAttribute("sendId",storeId);
    	model.addAttribute("storeInfo", storeInfo);
    	model.addAttribute("userType", user.getUserType());
    	session.setAttribute("goodsListss", list0);
    	return "modules/sys/order/replaceOrderShow";
	}
    
      @ResponseBody
      @RequiresPermissions("sys:orders:view")
	  @RequestMapping(value = "userAddress")
      public List<SysAddress> userAddress(String userId){
    	  return addressService.selectByUseId(userId);
      }
    
     
    @RequestMapping(value = "saveAddress")
  	@ResponseBody
  	public SysAddress saveAddress(SysAddress address, HttpServletRequest request, HttpServletResponse response, Model model,String userId) {
  		address.setUserId(userId);
  		//如果保存的地址勾选了默认，则去除之前默认的地址
  		if("1".equals(address.getIsDef())){
  			SysAddress defAddress = addressService.getDefAddress(address);
  			if(defAddress!=null){
  				defAddress.setIsDef("0");
  				addressService.save(defAddress);
  			}
  		}
  		address.setDelFlag("0");
  		addressService.save(address);
  		return address;
  	}
      
    
    
    
    @RequestMapping(value = "getProvince")
	@ResponseBody
	public List<Area> getProvince(SysAddress address, HttpServletRequest request, HttpServletResponse response, Model model) {
		return areaService.getProvince();
	}
	
	@RequestMapping(value = "selectByParent")
	@ResponseBody
	public List<Area> selectByParent(Area areas, HttpServletRequest request, HttpServletResponse response, Model model) {
		return areaService.selectByParent(areas.getId());
	} 
	
	@RequestMapping(value = "getAddress")
	@ResponseBody
	public SysAddress getAddress(SysAddress address, HttpServletRequest request, HttpServletResponse response, Model model) {
		return addressService.selectByAddressId(address.getId());
	}
	
	
	@RequestMapping(value = "isSatisfyFree")
	@ResponseBody
	public FreeWaybill isSatisfyFree(FreeWaybill freeWaybill,String provinceId, RedirectAttributes redirectAttributes,String sendId) {
		freeWaybill.setReceiveAreaId(provinceId);
		freeWaybill.setSendAreaId(sendId);
		return freeWaybillService.getWebFreeWaybillByArea(freeWaybill);
	}
	
	//下一步结算
	@RequiresPermissions("sys:orders:view")
	@RequestMapping(value = "nextConFirm")
	public String nextConFirm(HttpServletRequest request,HttpSession session,RedirectAttributes redirectAttributes){
		String addressId = request.getParameter("addressId");
		String transportType = request.getParameter("transportType");
		String[] goodsNum = request.getParameterValues("goodsNum");
		String[] goodsId = request.getParameterValues("goodsId");
		String userId = request.getParameter("userId");
		String storeCode = request.getParameter("storeCode");
		List<Goods> goodsList=new ArrayList<>();
		User us = UserUtils.getUser();
		Double totalMoney=0.0;
		for (int i = 0; i < goodsId.length; i++) {
			Goods goods=goodsService.get(goodsId[i]);
			totalMoney=totalMoney+goods.getPrice()*Integer.valueOf(goodsNum[i]);
			goods.setGoodsNum(Integer.valueOf(goodsNum[i]));
			goodsList.add(goods);
		   }
		    //信用额度调整
		    String code=getOrderReturnCode();
		    YongUser users=yongUserService.get(userId);
		    Credit credit=new Credit();
			Credit cr=creditService.selectByUserId(userId);
			credit.setUseMoney(cr.getUseMoney().add(new BigDecimal(totalMoney)));
			credit.setUserId(userId);
			credit.setUpdateDate(new Date());
			creditService.updateUseMoney(credit);
		
		    //额度流水表
			SysAddress addr=addressService.selectByAddressId(addressId);
			UserStore userStore=new UserStore();
			userStore.setUserId(userId);
			userStore.setStoreCode(storeCode);
			Orders order=new Orders();
			if(users.getBeStoreCode().equals(storeCode)){
				order.setSysUserId(users.getBeSysUserId());
			}
			order.setMoney(totalMoney.toString());
			if("1".equals(transportType)){
				Double totalMone=totalMoney*1.1;
				order.setPayMoney(totalMone.toString());
				order.setFreight(String.valueOf(totalMoney*0.1));
			}else{
				order.setPayMoney(totalMoney.toString());
			}
			if(addr!=null){
			order.setReceiveAddress(addr.getAddress());
			order.setReceivePhone(addr.getPhone());
			order.setReceiveName(users.getLoginName());
			}
			order.setOrderType("3");
			order.setTransportType(transportType);
			order.setUserId(userId);
			order.setBuyStoreCode(storeCode);
			Store store=storeService.selectByCode(storeCode);
			order.setBuyStoreName(store.getCnName());
			order.setCreateDate(new Date());
			order.setUpdateDate(new Date());
			order.setCreateBy(us);
			order.setUpdateBy(us);
			order.setPayType("0");
			order.setCode(code);
			order.setUserId(userId);
			order.setIsHistory("0");
			order.setState("2");
			ordersService.save(order);
		 
			for (Goods goods : goodsList) {
				OrdersDetail ordersDetail=new OrdersDetail();
				ordersDetail.setOrdersCode(code);
				ordersDetail.setPartsCode(goods.getPartsCode());
				ordersDetail.setGoodsCnName(goods.getCnName());
				ordersDetail.setGoodsCode(goods.getCode());
				ordersDetail.setNum(goods.getGoodsNum().toString());
				ordersDetail.setPrice(goods.getPrice().toString());
				ordersDetail.setIsHistroy("0");
				ordersDetail.setCreateDate(new Date());
				ordersDetail.setCreateBy(us);
				ordersDetailService.save(ordersDetail);
			}
			addMessage(redirectAttributes, "代下单成功");
			return REDIRECT+Global.getAdminPath()+"/sys/orders/showReplaceOrder?ps=1";
	}
	
	public String getOrderReturnCode(){
		String format = "%02d";
		Date nowDate = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat(YYYYMMDDHHMMSS);
		String now = sdf.format(nowDate);
		int orderCode = getMaxOrderReturnCode(now);
		orderCode = orderCode+1;
		format = now+format;
		return String.format(format, orderCode);
	}
	
	private int getMaxOrderReturnCode(String now){
		
		String code = ordersService.findMaxCode(now);
		if(code!=null){
			return Integer.parseInt(code.substring(14));
		}else{
			return 0;
		}
	}
	
	@RequestMapping(value = "/wuInformatin")
	public String  wuInformatin(String orderCode,Model model){
		List<Waybill>  webWaybill = waybillService.selectByOrderCode(orderCode);
		model.addAttribute("webWaybill", webWaybill);
		return "modules/sys/order/wuInformation";
	}
	
	//物流数据
	@ResponseBody
	@RequestMapping(value = "/waybillData")
	public List<Waybill> waybillData(String wuCode){
		return waybillService.selectByLogisticsCode(wuCode);
	}
}